﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Controllers
{
	using System.Web.Mvc;
	using Falcon.Core.Domain;
	using Falcon.Core.Domain.Enums;
	using Falcon.Core.Domain.Services;
	using Falcon.Core.Domain.Values;
	using Falcon.Core.Extensions;
	using Falcon.Core.Validation;

	public class UserController : DefaultController
	{
		public UserController(
			IAuthenticationService authenticationService,
			IUserService userService,
			IUserAlbumService userAlbumService,
			IUserGroupService userGroupService,
			IUserContactService userContactService)
		{
			this.AuthenticationService = authenticationService;
			this.UserService = userService;
			this.UserAlbumService = userAlbumService;
			this.UserGroupService = userGroupService;
			this.UserContactService = userContactService;
		}

		public IAuthenticationService AuthenticationService
		{
			get;
			private set;
		}

		public IUserService UserService
		{
			get;
			private set;
		}

		public IUserAlbumService UserAlbumService
		{
			get;
			private set;
		}

		public IUserGroupService UserGroupService
		{
			get;
			private set;
		}

		public IUserContactService UserContactService
		{
			get;
			private set;
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Index(SortUser sort, SortOrder order, int? page)
		{
			var users = UserService.GetPaged(new UserSpecification
			{
				Sort = sort,
				Order = order,
				Page = page,
				Limit = Settings.Users.PageLimit
			});

			return View(Views.Index, users);
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Detail(int id, string slug, string mode, int? page)
		{
			var user = UserService.GetById(id);

			if (user == null)
			{
				return Error(Resources.Messages.UserNotFound);
			}

			switch (mode.AsEnum<UserViewMode>())
			{
				case UserViewMode.Albums:
					{
						user.Albums = UserAlbumService.GetPhotos(new UserAlbumSpecification
						{
							UserId = user.Id,
							Page = page,
							Limit = Settings.Users.AlbumPageLimit
						});

						return View("{0}_{1}".Fmt(Views.Detail, Views.Albums), user);
					}
				case UserViewMode.Groups:
					{
						user.Groups = UserGroupService.GetPaged(new UserGroupSpecification
						{
							UserMemberId = user.Id,
							Page = page,
							Limit = Settings.Users.GroupPageLimit
						});

						return View("{0}_{1}".Fmt(Views.Detail, Views.Groups), user);
					}
				case UserViewMode.Friends:
					{
						user.Friends = UserContactService.GetPaged(new UserContactSpecification
						{
							UserId = user.Id,
							IsModeEnabled = false,
							Status = new[] { UserContactStatus.FriendApproved },
							Page = page,
							Limit = Settings.Users.ContactPageLimit
						});

						return View("{0}_{1}".Fmt(Views.Detail, Views.Friends), user);
					}
				default:
					{
						return View(Views.Detail, user);
					}
			}
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Create()
		{
			return View(Views.Create, new UserCreate());
		}

		[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
		public ActionResult Create(UserCreate value)
		{
			try
			{
				var user = UserService.Create();

				UserService.Insert(user, value);

				return Status(Resources.Messages.UserAccountCreated);
			}
			catch (ValidationException exception)
			{
				ModelState.CopyValidationExceptions(exception);
			}

			return View(Views.Create, value);
		}

		[AcceptVerbs(HttpVerbs.Get), Authorize]
		public ActionResult Update()
		{
			var user = UserService.GetById(Identity.Id);

			if (user == null)
			{
				return Error(Resources.Messages.UserNotFound);
			}

			return user.CanUpdate ? View(Views.Update, new UserUpdate(user)) : NotAuthorized();
		}

		[AcceptVerbs(HttpVerbs.Post), Authorize, ValidateAntiForgeryToken]
		public ActionResult Update(UserUpdate value)
		{
			try
			{
				var user = UserService.GetById(Identity.Id);

				if (user == null)
				{
					return Error(Resources.Messages.UserNotFound);
				}

				if (!user.CanUpdate)
				{
					return NotAuthorized();
				}

				UserService.Update(user, value);

				if (user.Id.Equals(Identity.Id) && value.EmailAddressChanged)
				{
					AuthenticationService.Logout();
				}

				Application.SessionDestroy();

				return Message(Routes.UserUpdate, Resources.Messages.UserAccountUpdated);
			}
			catch (ValidationException exception)
			{
				ModelState.CopyValidationExceptions(exception);
			}

			return View(Views.Update, value);
		}
	}
}